package cc.ufinity.networkdiagnose.widget;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.adapter.TestTaskListAdapter;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.WlanManager;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.view.R;
import cc.ufinity.networkdiagnose.view.WelcomeActivity;

public class TaskTestGSMWidget extends GeneralTestWidget {
	public final static String PREFS_NAME = "mymobile";
	public final static String PREFS_KEY = "number";

	public boolean isGetJWDOver=false;
	public boolean isOver=false;
	
	private Thread thread;
	public static Activity ctx;
	private static String TAG = "TaskWidget";
	private ListView taskListView;
	private List<Task> tasks = null;
	private TelManager tm;
	private Handler handler;
	private String myPhoneNumber;
	private List<Map<String, Object>> datas;
	private TestTaskListAdapter tAdapter = null;
	private ImageView image1 = null, image2 = null;
	private ProgressBar pb1 = null, pb2 = null;
	private Button begin_test = null;
	private TextView tv_progress1 = null, tv_progress2 = null;
	private LinearLayout linearlayout = null;
	private int testNum;
	private Button resultButton;
	private TextView titleView;
	private Task task;
	private WlanManager wlanManager;
	private boolean connected = false;
	private boolean connected2 = false;
	private boolean btnClick = false;
private int num=1;
	public boolean isTesting = true;

	public TaskTestGSMWidget(Activity context) {
		super(context);
		this.ctx = context;
		GlobalApp.taskTestGSMWidget = this;
		GlobalApp.nowNetType = 3;
		GlobalApp.clearAll();
		inflate(context, R.layout.task_test_widget_gsm, this);
		linearlayout = (LinearLayout) this
				.findViewById(R.id.progress_linearlayout_gsm);
		image1 = new ImageView(ctx);
		image1.setBackgroundResource(R.drawable.test_before);
		image2 = new ImageView(ctx);
		image2.setBackgroundResource(R.drawable.test_after);
		linearlayout.addView(image1, new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));
		pb2 = (ProgressBar) findViewById(R.id.progress2_gsm);
		tv_progress1 = (TextView) findViewById(R.id.tv_progress1_gsm);
		tv_progress2 = (TextView) findViewById(R.id.tv_progress2_gsm);
		titleView = (TextView) findViewById(R.id.task_test_title_gsm);

		begin_test = (Button) findViewById(R.id.begin_tesk_gsm);
		begin_test.setText("测试中...");
		 
		wlanManager = new WlanManager(ctx);
		// task = (Task)
		// ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);//获取任务
		task = GlobalApp.taskGSM;
		if (task.taskType == null) {
			titleView.setText("GSM网络测试");
		} else {
			if (task.taskType.trim().equals("巡检测试")) {
				titleView.setText("GSM巡检测试");
			} else if (task.taskType.trim().equals("验收测试")) {
				titleView.setText("GSM验收测试");
			} else {
				titleView.setText("GSM网络测试");
			}
		}
		titleView.setText("GSM测试");
		System.out.println("GSM测试选择的网络是： "
				+ (task.selNetType == ConnectivityManager.TYPE_MOBILE));

		begin_test.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (btnClick) {
					ctx.setContentView(new TaskTestResult(ctx));
					btnClick = false;
				}
			}
		});
		taskListView = (ListView) this.findViewById(R.id.taskTestListView_gsm);
		taskListView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Map<String, Object> r = (Map<String, Object>) taskListView
						.getAdapter().getItem(position);
				Log.d("结果查看", "详细信息: " + r.toString());
			}
		});

		handler = new Handler() {
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case MessageWhat.TASK_LIST_LOADED_SUCCESS:
					init();
					dismissMessageDialog();
					break;
				case MessageWhat.TASK_LIST_LOADED_FAILED:
					dismissMessageDialog();
					showMessage(ctx, "获取任务列表失败.");
					break;
				case 2:
					showMessage(ctx, "本机手机号码无法获取.");
					dismissMessageDialog();
					break;
				case MessageWhat.WIFI_SUCESS_CONNECTED:
					if(num==1){
						num=2;
						dismissMessageDialog();
						task.acIp = wlanManager.getIpAddress();
						ctx.getIntent().putExtra(TAG_REFER_TASK, task);
						start();
					} 
					break;
				}
			}
		};
		wlanManager.setHandler(handler);
		tm = new TelManager(ctx);
		tm.setHandler(handler);
		connectNetWork();
		
		
		new Thread(){
			public void run(){
				while(!isOver){
					if(isGetJWDOver){
						isOver=true;
						Message message = handlerChildMessage.obtainMessage();
						message.arg1 = MessageWhat.HANDLER_START;
						message.sendToTarget();
					}
				}
			}
		}.start();
	}

	private void connectNetWork() {
		showMessageDialog(ctx, "正在连接网络...");
		thread = new Thread() {
			@Override
			public void run() {
				if (wlanManager.checkNetworkType() == 5) {
					wlanManager.sendMsg(MessageWhat.WIFI_SUCESS_CONNECTED);
				} else {
					wlanManager.closeWifi();
					while (!connected2) {
						// System.err.println(wlanManager.checkNetworkType()+"====================="+wlanManager.setMobileDataEnabled(true));
						wlanManager.setMobileDataEnabled(true);
						if (wlanManager.checkNetworkType() == 5) {
							System.err.println("=====================3");
							connected2 = true;
							wlanManager
									.sendMsg(MessageWhat.WIFI_SUCESS_CONNECTED);
						}
						try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
						}
					}
				}

			}
		};

		thread.start();
	}

	Handler handlerChildMessage = new Handler() {

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message messag) {
			if (isTesting) {
				Message msg = updateHandler.obtainMessage();
				Message message = new Message();
				Object tempObject;
				Map<String, Object> t2;
				if (datas != null && datas.size() > 0) {
					switch (messag.arg1) {
					case MessageWhat.HANDLER_START:
						testNum = 0;
						/*
						 * System.out.println("= = = = GSM PING测试 = = = =");
						 * msg.arg1 = testNum; testNum = testNum +1;
						 * updateHandler.sendMessage(msg); tempObject =
						 * taskListView.getAdapter().getItem(testNum); t2 =
						 * tempObject==null?null:(Map<String, Object>)
						 * tempObject; if(t2!=null && t2.get("taskSkip")!=null
						 * &&t2.get("taskSkip").equals("0")) { new
						 * PingWidgetProxy(ctx, handlerChildMessage); } else {
						 * message.arg1 = MessageWhat.HANDLER_PING;
						 * GlobalApp.result_PING_test=new
						 * StringBuffer("\n\nPING测试项已跳过"); } break;
						 */
						msg.arg1 = testNum;
						System.out
						.println("= = = =  正在进行GSM的  信号强度测试= =111111111 = =     "+testNum);
						new RssiTestWidgetProxy(ctx, handlerChildMessage);
						testNum = testNum + 1;
						updateHandler.sendMessage(msg);
						tempObject = taskListView.getAdapter().getItem(testNum);
						t2 = tempObject == null ? null
								: (Map<String, Object>) tempObject;
						if (t2 != null && t2.get("taskSkip") != null
								&& t2.get("taskSkip").equals("0")) {
							//new RssiTestWidgetProxy(ctx, handlerChildMessage);
							System.err
									.println("= = = =  正在进行GSM的  信号强度测试= = = =");
						} else {
							message.arg1 = MessageWhat.HANDLER_RSSI;
							GlobalApp.result_SRRI_test = new StringBuffer(
									"\n\n信号强度测试项已跳过");
						}
						/*
						 * msg.arg1 = testNum; //
						 * updateHandler.sendMessage(msg); tempObject =
						 * taskListView.getAdapter().getItem(testNum); t2 =
						 * tempObject==null?null:(Map<String, Object>)
						 * tempObject; if(t2!=null && t2.get("taskSkip")!=null
						 * && t2.get("taskSkip").equals("0")) { new
						 * HttpTestWidgetProxy(ctx, handlerChildMessage); } else
						 * { message.arg1 = MessageWhat.HANDLER_HTTP;
						 * GlobalApp.result_HTTP_test=new
						 * StringBuffer("\n\nHTTP测试项已跳过"); } break;
						 */
						break;
					case MessageWhat.HANDLER_HTTP:
						/*
						 * System.out.println("= = = =  收到消息1   = = = =");
						 * msg.arg1 = testNum; testNum = testNum +1;
						 * updateHandler.sendMessage(msg); tempObject =
						 * taskListView.getAdapter().getItem(testNum); t2 =
						 * tempObject==null?null:(Map<String, Object>)
						 * tempObject; if(t2!=null && t2.get("taskSkip")!=null
						 * && t2.get("taskSkip").equals("0")) { new
						 * FtpTestProxyWidget(ctx, handlerChildMessage,
						 * tAdapter); } else { message.arg1 =
						 * MessageWhat.HANDLER_FTP;
						 * GlobalApp.result_FTP_test=new
						 * StringBuffer("\n\nFTP测试项已跳过"); }
						 */
						System.out.println("---------FTP已经是取消测试了----------");
						break;
					case MessageWhat.HANDLER_FTP:
						/*
						 * System.out.println("= = = =  收到消息2   = = = =");
						 * msg.arg1 = testNum;
						 * testNum = testNum +1;
						 * updateHandler.sendMessage(msg); tempObject =
						 * taskListView.getAdapter().getItem(testNum); t2 =
						 * tempObject==null?null:(Map<String, Object>)
						 * tempObject; if(t2!=null && t2.get("taskSkip")!=null
						 * &&t2.get("taskSkip").equals("0")) { new
						 * PingWidgetProxy(ctx, handlerChildMessage); } else {
						 * message.arg1 = MessageWhat.HANDLER_PING;
						 * GlobalApp.result_PING_test=new
						 * StringBuffer("\n\nPING测试项已跳过"); }
						 */

						break;
					case MessageWhat.HANDLER_PING:
						/*System.out.println(testNum+"= = = =  收到消息4 4444444444444444  = = = =");
						msg.arg1 = testNum;
						testNum = testNum + 1;
						updateHandler.sendMessage(msg);
						tempObject = taskListView.getAdapter().getItem(testNum);
						t2 = tempObject == null ? null
								: (Map<String, Object>) tempObject;
						if (t2 != null && t2.get("taskSkip") != null
								&& t2.get("taskSkip").equals("0")) {
							new RssiTestWidgetProxy(ctx, handlerChildMessage);
						} else {
							message.arg1 = MessageWhat.HANDLER_RSSI;
							GlobalApp.result_SRRI_test = new StringBuffer(
									"\n\n信号强度测试项已跳过");
						}*/
						break;
					case MessageWhat.HANDLER_RSSI:
						System.out.println(testNum+ "   = = = =  收到消息555555555555555555   = = = =");
						msg.arg1 = testNum;
						testNum = testNum + 1;
						updateHandler.sendMessage(msg);
						isTesting = false;
						// btnClick = true;
						// begin_test.setText("查看结果");
						break;
					}
					handlerChildMessage.sendMessage(message);
				}
			}
		}
	};

	/**
	 * 获取经纬度
	 */
	public void getJWD(){
		try{
			WelcomeActivity.mLocClient.start();
		}catch(Exception e){ }
		new Thread(){
			public void run(){
				try {
					Thread.sleep(10*1000);
					isGetJWDOver=true;
					WelcomeActivity.mLocClient.stop();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	
	Thread updateThread = new Thread() {

		@Override
		// 15948847685
		public void run() {
			// TODO Auto-generated method stub
			pb2.setMax(datas.size());
		}
	};
	Handler updateHandler = new Handler() {
		private String testingName = "";
		public void handleMessage(Message msg) {
			if (msg.arg1 == -1) {
				ProgressBar pb = new ProgressBar(ctx);
				pb.setVisibility(VISIBLE);
				linearlayout.removeAllViews();
				linearlayout.addView(pb, new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				@SuppressWarnings("unchecked")
				Map<String, Object> t = (Map<String, Object>) taskListView
						.getAdapter().getItem(msg.arg1 + 1);
				testingName = t == null ? "" : (String) t.get("taskName");
				if (t != null && t.get("taskSkip") != null
						&& t.get("taskSkip").equals("0")) {
					t.put("taskState", "3");
				} else if (t != null && t.get("taskSkip") != null
						&& t.get("taskSkip").equals("1")) {
					System.out.println(testingName + " 已跳过");
				}

			} else if (msg.arg1 < datas.size() - 1) {
				@SuppressWarnings("unchecked")
				Map<String, Object> t1 = (Map<String, Object>) taskListView
						.getAdapter().getItem(msg.arg1);
				@SuppressWarnings("unchecked")
				Map<String, Object> t2 = (Map<String, Object>) taskListView
						.getAdapter().getItem(msg.arg1 + 1);
				testingName = t2 == null ? "" : (String) t2.get("taskName");
				if (t1 != null && t1.get("taskSkip") != null
						&& t1.get("taskSkip").equals("0")) {
					t1.put("taskState", "1");
				} else if (t1 != null && t1.get("taskSkip") != null
						&& t1.get("taskSkip").equals("1")) {
					System.out.println(t1.get("taskName") + " 已跳过");
				}
				if (t2 != null && t2.get("taskSkip") != null
						&& t2.get("taskSkip").equals("0")) {
					t2.put("taskState", "3");
				} else if (t2 != null && t2.get("taskSkip") != null
						&& t2.get("taskSkip").equals("1")) {
					System.out.println(t2.get("taskName") + " 已跳过");
				}
			} else if (msg.arg1 == datas.size() - 1) {
				@SuppressWarnings("unchecked")
				Map<String, Object> t = (Map<String, Object>) taskListView
						.getAdapter().getItem(msg.arg1);
				if (t != null && t.get("taskSkip") != null
						&& t.get("taskSkip").equals("0")) {
					t.put("taskState", "1");
				} else if (t != null && t.get("taskSkip") != null
						&& t.get("taskSkip").equals("1")) {
					System.out.println(t.get("taskName") + " 已跳过");
				}
			}

			if (msg.arg1  >= datas.size()) {
				System.out.println("-----检测完毕-------------tv_progress2.setText()-------------------------");
				tv_progress2.setText("检测完毕");
				btnClick = true;
				begin_test.setText("查看结果");
				linearlayout.removeAllViews();
				linearlayout.addView(image2, new LayoutParams(
						LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
				// =============================自动跳转到测试结果页面上传结果
				if (btnClick) {

					task.endsTime = StringUtils.getDateTime();

					if (GlobalApp.isWlanFirst) {

						if (GlobalApp.TDorGSM_task.equals(WlanManager.TD)) {
							if (GlobalApp.taskOtherList.size() > 0) {
								ctx.setContentView(new Test_Task_Widget_Other(
										ctx));
							} else {
								ctx.setContentView(new TaskTestResultAll(ctx));
							}
						} else if (GlobalApp.TDorGSM_task
								.equals(WlanManager.GSM)) {
							if (tm.getNetworkType() != null
									&& (tm.getNetworkType().equals(
											WlanManager.GSM) || tm
											.getNetworkType().equals("GPRS"))) {
								showAlertDialog(ctx,
										"当前网络类型为GSM模式，进行TD测试请先切换至TD网络类型.");
							} else {
								ctx.setContentView(new TaskTestTDWidget(ctx)); // 直接跳转到TD网络测试
							}
						} else {
							ctx.setContentView(new TaskTestResultAll(ctx));
						}
					} else {
						ctx.setContentView(new TaskTestResultGSM(ctx));
					}

					btnClick = false;
				}
				ctx.getIntent().putExtra(TAG_REFER_TASK, task);
				// ================================================================

			} else {
				tv_progress2.setText("正在检测第" + (msg.arg1 + 2) + "项："
						+ testingName);
			}

			tv_progress1.setText("总进度：" 
					+ "100%");
			pb2.setProgress(msg.arg1 + 1);
			tAdapter.notifyDataSetChanged(); // 更新Adapter
		}
	};

	public void start() {
		if (NetworkManager.detectNetworkConnectivity(ctx) == -1) {
			showMessage(ctx, "无法连接至因特网.");
			return;
		}
		myPhoneNumber = tm.getPhoneNumber();
		if (StringUtils.isEmpty(myPhoneNumber)) {
			showMessage(ctx, "获取本机号码失败,请输入.");
			showInputDialog();
			return;
		} else {
			loadTaskList();
		}
	}

	private void showInputDialog() {
		LayoutInflater factory = LayoutInflater.from(ctx);
		final View dialogView = factory.inflate(
				R.layout.input_phone_num_dialog, null);
		final EditText inputText = (EditText) dialogView
				.findViewById(R.id.phoneNumEditText);
		AlertDialog.Builder inputBuilder = new AlertDialog.Builder(ctx);
		inputBuilder.setTitle("提示");
		// inputBuilder.setIcon(R.drawable.smile);
		inputBuilder.setView(dialogView);
		inputBuilder.setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						if (StringUtils.isEmpty(inputText.getText().toString())) {
							try {
								Field field = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(dialog, false);
							} catch (Exception e) {
								e.printStackTrace();
							}
							showMessage(ctx, "请输入本机号码");
						} else {
							try {
								Field field = dialog.getClass().getSuperclass()
										.getDeclaredField("mShowing");
								field.setAccessible(true);
								field.set(dialog, true);
							} catch (Exception e) {
								e.printStackTrace();
							}
							myPhoneNumber = inputText.getText().toString();
							SharedPreferences settings = ctx
									.getSharedPreferences(PREFS_NAME, 0);
							SharedPreferences.Editor editor = settings.edit();
							editor.putString(PREFS_KEY, myPhoneNumber);
							editor.commit(); // 保存手机号码

							dialog.cancel();
							loadTaskList();
						}
					}
				});
		inputBuilder.setNegativeButton("取消",
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							Field field = dialog.getClass().getSuperclass()
									.getDeclaredField("mShowing");
							field.setAccessible(true);
							field.set(dialog, true);
						} catch (Exception e) {
							e.printStackTrace();
						}
						dialog.cancel();
					}
				});
		Dialog dialog = inputBuilder.create();
		dialog.show();
	}

	private void loadTaskList() {
		// this.showMessageDialog(ctx, "正在加载任务列表...");
		new Thread() {
			public void run() {
				getTasks();
			}
		}.start();
	}

	private void init() {
		tAdapter = new TestTaskListAdapter(ctx, datas);
		taskListView.setAdapter(tAdapter);
		task.startTime = StringUtils.getDateTime();
		task.startsTime = StringUtils.getDateTime();
		testNum = 0;
		pb2.setMax(datas.size());
		//GeneralTestWidget.writeToSDcardFile("createXmlMessage.txt", "正在采集GSM文件所需的数据");
		Message msg = new Message();
		msg.arg1 = -1;
		updateHandler.sendMessage(msg);

		System.out.println("-----------------------------------------------------------------   查看测试的次数");
		getJWD();
	}

	private List<Map<String, Object>> getTasks() {
		List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();

		try {
			tasks = new ArrayList<Task>();
			Task tk0 = new Task();
			Task tk1 = new Task();
			Task tk2 = new Task();
			Task tk3 = new Task();
			Task tk4 = new Task();
			Task tk5 = new Task();
			Task tk6 = new Task();
			Task tk7 = new Task();
			Task tk8 = new Task();
			Task tk9 = new Task();
			Task tk = new Task();
			tk0.taskName = "HTTP测试";
			tk1.taskName = "FTP测试";
			tk2.taskName = "PING测试";
			tk3.taskName = "AP关联";
			tk4.taskName = "WEB认证";
			tk5.taskName = "PEAP认证";
			tk6.taskName = "SIM认证";
			tk7.taskName = "隔离测试";
			tk8.taskName = "经纬度测试";
			tk9.taskName = "信噪比测试";
			tk.taskName = "RSSI和经纬度";

			// tasks.add(tk0);
			// tasks.add(tk1);
			// tasks.add(tk2);
			// tasks.add(tk9);
			tasks.add(tk);
			//tasks.add(tk8);

			Map<String, Object> t = null;
			for (Task task : tasks) {
				t = new HashMap<String, Object>();
				t.put("taskName", task.taskName);
				t.put("taskState", "0"); // 检测状态
				t.put("taskSkip", "0"); // 是否跳过

				res.add(t);
			}
			datas = res;
			Message e = new Message();
			e.what = MessageWhat.TASK_LIST_LOADED_SUCCESS;
			handler.sendMessage(e);

		} catch (Exception e) {
			Log.e(TAG, "解析XML任务时出错：", e);
			Message e1 = new Message();
			e1.what = MessageWhat.TASK_LIST_LOADED_FAILED;
			handler.sendMessage(e1);
		}
		return res;
	}

	public void showAlertDialog(final Activity ctx, final String message) {
		System.out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABBBBBBBBBBBBBBBBBB");
		AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
		builder.setTitle("测试提示");
		builder.setMessage(message);
		builder.setCancelable(false);
		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				try {
					ctx.getIntent().putExtra(
							MessageWhat.INDEX_Test_Task_Widget_GSM_WIDGET2, 1);
					Intent intent = new Intent(Intent.ACTION_MAIN);
					intent.setClassName("com.android.phone",
							"com.android.phone.NetworkSetting");
					ctx.startActivity(intent);
					GlobalApp.isWlanTO_TD_GSM = true;
					dialog.cancel();
				} catch (Exception e) {
					showAlertDialog(ctx, message);
					showMessage(ctx, "该手机不支持TD/GSM网络切换");
				}
			}
		});
		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				if (GlobalApp.taskOtherList.size() == 0) {
					ctx.setContentView(new TaskTestResultAll(ctx));
				} else {
					ctx.setContentView(new Test_Task_Widget_Other(ctx));
				}
				dialog.cancel();
			}
		});
		wifiListDialog = builder.create();
		wifiListDialog.show();
	}
}
